package com.mrx.xfriendship.converter;

import com.mrx.xfriendship.model.SecurityUser;
import com.mrx.xfriendship.model.dto.SecurityUserDTO;
import com.mrx.xfriendship.model.dto.UserDTO;
import com.mrx.xfriendship.model.po.UserDetailPO;
import com.mrx.xfriendship.model.po.UserPO;
import com.mrx.xfriendship.model.vo.RegisterUserVO;
import com.mrx.xfriendship.model.vo.UserInfoVO;
import com.mrx.xfriendship.service.IMinioService;
import org.mapstruct.*;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;
import java.util.Collections;

/**
 * @author : 肖康宁
 * @since : 2022-12-09 13:37
 **/
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING,
        imports = Collections.class,
        unmappedTargetPolicy = ReportingPolicy.IGNORE
)
public abstract class UserConverter implements IConverter<UserPO, UserDTO> {

    @Resource
    private PasswordEncoder encoder;

    @Resource
    protected IMinioService minioService;

    @Mapping(target = "pass", qualifiedByName = "encodePass")
    public abstract UserPO toPO(RegisterUserVO vo);

    @Mapping(target = "pass", source = "vo.newPassword", qualifiedByName = "encodePass")
    public abstract UserPO toPO(Integer id, UserInfoVO vo);

    @Mapping(target = "registerDate", expression = "java( po.getCreateTime() )")
    @Mapping(target = "avatar", expression = "java( minioService.preview(po.getUserDetail().getAvatar()) )")
    @Mapping(target = "role", expression = "java( po.getUserDetail().getRole().getRole() )")
    public abstract UserDTO toDTO(UserPO po);

    @Mapping(target = "role", expression = "java( po.getUserDetail().getRole().getRole() )")
    public abstract SecurityUserDTO toSecurityUserDTO(UserPO po);

    @Mapping(target = "role", expression = "java( Collections.singletonList(po.getUserDetail().getRole().getRole()) )")
    public abstract SecurityUser toSecurityUser(UserPO po);

    public UserDetailPO toUserDetail(UserPO userPO) {
        UserDetailPO record = new UserDetailPO();
        record.setAvatar("20230121/69c09d7b121aa6dc9fbc4b2bbe76bc4b.jpg");
        record.setUserId(userPO.getId());
        return record;
    }

    @Named("encodePass")
    @SuppressWarnings("unused")
    protected String encode(String rawPass) {
        return encoder.encode(rawPass);
    }

}
